package com.wish.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Service;

import com.wish.model.CommonConstants;
import com.wish.model.User;

@Service
public class UserDao
{
	@PersistenceContext
	private EntityManager em;

	@SuppressWarnings("unchecked")
	public User getUserByUserName(String userName) throws RuntimeException
	{
		Query query = em.createQuery("select user from User user where userName=?1");
		query.setParameter(1, userName);
		List<User> users = query.setMaxResults(1).setFirstResult(0).getResultList();
		if (users.size() == 0)
		{
			return new User();
		}
		return users.get(0);
	}

	public void insert(User user) throws RuntimeException
	{
		em.persist(user);
	}

	public void delete(long id) throws RuntimeException
	{
		em.remove(em.find(User.class, id));
	}

	@SuppressWarnings("unchecked")
	public List<User> getList(long groupID)
	{
		String sql = "select u from User u";
		if (groupID != CommonConstants.ALL)
		{
			sql = sql + " where u.group.id=?1";
		}
		Query query = em.createQuery(sql);

		if (groupID != CommonConstants.ALL)
		{
			query.setParameter(1, groupID);
		}
		return query.getResultList();
	}
}
